<template>
  <div class="todo-list-page">
    <!-- 头部工具栏 -->
    <div class="todo-header">
      <div class="header-left">
        <div class="stats">
          <el-tag type="info">总计 {{ stats.total }}</el-tag>
          <el-tag type="warning">进行中 {{ stats.inProgress }}</el-tag>
          <el-tag type="success">已完成 {{ stats.completed }}</el-tag>
          <el-tag>完成率 {{ stats.completionRate }}%</el-tag>
        </div>
      </div>
      <div class="header-right">
        <div class="view-controls">
          <el-button-group>
            <el-button
                :type="viewMode === 'grid' ? 'primary' : 'default'"
                :icon="Grid"
                @click="viewMode = 'grid'"
                :title="`网格视图 (${formatShortcut(shortcuts[3])})`"
            />
            <el-button
                :type="viewMode === 'list' ? 'primary' : 'default'"
                :icon="List"
                @click="viewMode = 'list'"
                title="列表视图"
            />
            <el-button
                :type="viewMode === 'flexbox' ? 'primary' : 'default'"
                :icon="Operation"
                @click="viewMode = 'flexbox'"
                title="弹性布局视图"
            />
          </el-button-group>
        </div>
        <el-button
            type="primary"
            :icon="Plus"
            @click="handleCreateTodo"
            :title="`新建待办 (${formatShortcut(shortcuts[0])})`"
        >
          新建待办
        </el-button>
        <el-button
            :icon="QuestionFilled"
            @click="showShortcutsDialog = true"
            title="查看快捷键"
            circle
        />
      </div>
    </div>

    <!-- 过滤器工具栏 -->
    <div class="filter-toolbar">
      <div class="filter-row">
        <el-input
            v-model="filter.keyword"
            :placeholder="`搜索待办事项... (${formatShortcut(shortcuts[1])})`"
            :prefix-icon="Search"
            clearable
            style="width: 300px; margin-right: 16px;"
            class="search-input"
        />

        <el-select
            v-model="filter.status"
            placeholder="状态"
            multiple
            clearable
            style="width: 150px; margin-right: 16px;"
        >
          <el-option
              v-for="status in statusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
          />
        </el-select>

        <el-select
            v-model="filter.priority"
            placeholder="优先级"
            multiple
            clearable
            style="width: 150px; margin-right: 16px;"
        >
          <el-option
              v-for="priority in priorityOptions"
              :key="priority.value"
              :label="priority.label"
              :value="priority.value"
          />
        </el-select>

        <el-select
            v-model="selectedCategoryId"
            placeholder="分类"
            clearable
            style="width: 150px; margin-right: 16px;"
            @change="handleCategoryChange"
        >
          <el-option
              label="未分类"
              :value="-1"
          />
          <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
          />
        </el-select>

        <el-button
            @click="resetFilter"
            :title="`重置过滤器 (${formatShortcut(shortcuts[2])})`"
        >
          重置
        </el-button>
      </div>

      <div class="sort-row">
        <span class="sort-label">排序：</span>
        <el-select
            v-model="sort.field"
            style="width: 120px; margin-right: 8px;"
        >
          <el-option
              v-for="field in sortFields"
              :key="field.value"
              :label="field.label"
              :value="field.value"
          />
        </el-select>
        <el-select
            v-model="sort.order"
            style="width: 80px;"
        >
          <el-option label="升序" value="asc"/>
          <el-option label="降序" value="desc"/>
        </el-select>
      </div>
    </div>

    <!-- 待办事项列表 -->
    <div class="todo-list" v-loading="loading">
      <div v-if="todos.length === 0" class="empty-state">
        <el-empty description="暂无待办事项">
          <el-button type="primary" @click="handleCreateTodo">
            创建第一个待办事项
          </el-button>
        </el-empty>
      </div>

      <div v-else class="todo-items"
           :class="{ 'grid-view': viewMode === 'grid','flexbox-view': viewMode === 'flexbox' }">
        <!-- 列表视图 -->
        <template v-if="viewMode === 'list'">
          <TodoItemComponent
              v-for="todo in todos"
              :key="todo.id"
              :todo="todo"
              :category="getCategoryById(todo.categoryId || '')"
              :categories="categories"
              :show-category-name="showCategoryName"
              :selected="selectedTodoId === todo.id"
              @update="handleUpdateTodo"
              @delete="handleDeleteTodo"
              @toggle="handleToggleTodo"
              @detail="handleDetailTodo"
              @select="handleSelectTodo"
          />
        </template>

        <!-- 网格视图 -->
        <template v-else-if="viewMode === 'grid'">
          <TodoGridItem
              v-for="todo in todos"
              :key="todo.id"
              :todo="todo"
              :category="getCategoryById(todo.categoryId || '')"
              :categories="categories"
              :show-category-name="showCategoryName"
              :selected="selectedTodoId === todo.id"
              @update="handleUpdateTodo"
              @delete="handleDeleteTodo"
              @toggle="handleToggleTodo"
              @detail="handleDetailTodo"
              @select="handleSelectTodo"
          />
        </template>

        <!-- 弹性布局视图 -->
        <template v-else-if="viewMode === 'flexbox'">
          <TodoCompactItem
              v-for="todo in todos"
              :key="todo.id"
              :todo="todo"
              :category="getCategoryById(todo.categoryId || '')"
              :categories="categories"
              :show-category-name="showCategoryName"
              :selected="selectedTodoId === todo.id"
              @update="handleUpdateTodo"
              @delete="handleDeleteTodo"
              @toggle="handleToggleTodo"
              @detail="handleDetailTodo"
              @select="handleSelectTodo"
          />
        </template>
      </div>
    </div>

    <!-- 快捷键帮助对话框 -->
    <el-dialog
        v-model="showShortcutsDialog"
        title="键盘快捷键"
        width="400px"
        center
    >
      <div class="shortcuts-list">
        <div
            v-for="(shortcut, index) in shortcuts"
            :key="index"
            class="shortcut-item"
        >
          <span class="shortcut-description">{{ shortcut.description }}</span>
          <el-tag type="info" class="shortcut-key">
            {{ formatShortcut(shortcut) }}
          </el-tag>
        </div>
      </div>
      <template #footer>
        <el-button @click="showShortcutsDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, computed, onMounted, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {useRoute, useRouter} from 'vue-router'
import {Plus, Search, List, Grid, QuestionFilled, Operation} from '@element-plus/icons-vue'
import {useTodos} from '../composables'
import {TodoStatus, TodoPriority, type UpdateTodoRequest, type TodoItem} from '../types'
import TodoItemComponent from '../components/TodoItem.vue'
import TodoGridItem from '../components/TodoGridItem.vue'
import TodoCompactItem from '../components/TodoCompactItem.vue'
import {useKeyboard, type KeyboardShortcut} from '@/composables'

// 路由相关
const route = useRoute()
const router = useRouter()

// 使用待办事项管理
const {
  todos,
  categories,
  loading,
  filter,
  sort,
  stats,
  viewMode,
  updateTodo,
  deleteTodo,
  toggleTodoStatus,
  getCategoryById,
  resetFilter: originalResetFilter,
  applyFilter,
  autoInit,
  loadCategories
} = useTodos()

// 禁用自动初始化，我们需要手动控制
autoInit(false)

// 对话框控制
const showShortcutsDialog = ref(false)

// 选中的分类
const selectedCategoryId = ref<string | -1 | null>(null)

// 选中的待办事项ID
const selectedTodoId = ref<string | null>(null)

// 判断是否显示分类名（只有选中具体分类时不显示）
const showCategoryName = computed(() => {
  // 如果选中了具体分类（不是null也不是-1），则不显示分类名
  return !selectedCategoryId.value || selectedCategoryId.value === -1
})

// 定义快捷键
const shortcuts: KeyboardShortcut[] = [
  {
    key: 'n',
    ctrl: true,
    description: '新建待办事项',
    callback: () => {
      handleCreateTodo()
    }
  },
  {
    key: 'f',
    ctrl: true,
    description: '搜索待办事项',
    callback: () => {
      // 聚焦搜索框
      const searchInput = document.querySelector('.filter-toolbar input') as HTMLInputElement
      if (searchInput) {
        searchInput.focus()
      }
    }
  },
  {
    key: 'r',
    ctrl: true,
    description: '重置过滤器',
    callback: () => {
      resetFilter()
      ElMessage.success('过滤器已重置')
    }
  },
  {
    key: 'g',
    ctrl: true,
    description: '切换网格视图',
    callback: () => {
      viewMode.value = viewMode.value === 'list' ? 'grid' : 'list'
    }
  }
]

// 使用键盘快捷键
const {formatShortcutText: formatShortcut} = useKeyboard(shortcuts)

// 状态选项
const statusOptions = [
  {label: '待处理', value: TodoStatus.TODO},
  {label: '进行中', value: TodoStatus.IN_PROGRESS},
  {label: '已完成', value: TodoStatus.COMPLETED},
  {label: '已取消', value: TodoStatus.CANCELLED}
]

// 优先级选项
const priorityOptions = [
  {label: '紧急', value: TodoPriority.URGENT},
  {label: '高', value: TodoPriority.HIGH},
  {label: '中', value: TodoPriority.MEDIUM},
  {label: '低', value: TodoPriority.LOW}
]

// 排序字段选项
const sortFields = [
  {label: '创建时间', value: 'createdAt'},
  {label: '更新时间', value: 'updatedAt'},
  {label: '截止日期', value: 'dueDate'},
  {label: '优先级', value: 'priority'},
  {label: '标题', value: 'title'}
]

// 处理创建待办事项
const handleCreateTodo = () => {
  const query: Record<string, string> = {}

  // 如果当前选中了具体分类（非"全部"或"未分类"），则传递分类ID
  if (selectedCategoryId.value && selectedCategoryId.value !== -1) {
    query.categoryId = selectedCategoryId.value as string
  }

  router.push({
    path: '/todo/create',
    query
  })
}

// 处理更新待办事项
const handleUpdateTodo = async (id: string, request: UpdateTodoRequest | TodoItem) => {
  // 如果传入的是TodoItem，表示要编辑
  if ('createdTime' in request) {
    router.push({
      path: `/todo/edit/${id}`,
      query: route.query  // 保持当前所有查询参数
    })
    return
  }

  // 否则表示要更新
  try {
    await updateTodo(id, request as UpdateTodoRequest)
    ElMessage.success('更新成功')
  } catch (error) {
    ElMessage.error('更新失败：' + (error as Error).message)
  }
}

// 处理删除待办事项
const handleDeleteTodo = async (id: string) => {
  try {
    await deleteTodo(id)
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error('删除失败：' + (error as Error).message)
  }
}

// 处理切换完成状态
const handleToggleTodo = async (id: string) => {
  try {
    await toggleTodoStatus(id)
  } catch (error) {
    ElMessage.error('操作失败：' + (error as Error).message)
  }
}

// 处理查看待办详情
const handleDetailTodo = (id: string) => {
  // 保持当前的查询参数，特别是categoryId
  router.push({
    path: `/todo/detail/${id}`,
    query: route.query  // 保持当前所有查询参数
  })
}

// 处理待办事项选中
const handleSelectTodo = (id: string) => {
  // 如果点击的是已选中的项，则取消选中
  if (selectedTodoId.value === id) {
    selectedTodoId.value = null
  } else {
    selectedTodoId.value = id
  }
}

// 处理分类变化（顶部下拉选择）
const handleCategoryChange = (categoryId: string | -1 | null) => {
  if (categoryId === null) {
    selectedCategoryId.value = null
    filter.categoryId = undefined
  } else if (categoryId === -1) {
    selectedCategoryId.value = -1
    filter.categoryId = -1
  } else {
    selectedCategoryId.value = categoryId
    filter.categoryId = categoryId
  }

  // 更新路由参数
  updateRouteQuery()

  // 调用API重新加载数据
  applyFilter()
}

// 更新路由查询参数
const updateRouteQuery = () => {
  const query: Record<string, string> = {}

  // 收藏标识
  if (filter.isFavorite) {
    query.isFavorite = 'true'
  }

  // 分类ID
  if (filter.categoryId !== undefined) {
    query.categoryId = String(filter.categoryId)
  }

  // 状态筛选
  if (filter.status && filter.status.length > 0) {
    query.status = filter.status.join(',')
  }

  // 优先级筛选
  if (filter.priority && filter.priority.length > 0) {
    query.priority = filter.priority.join(',')
  }

  // 关键词搜索
  if (filter.keyword) {
    query.keyword = filter.keyword
  }

  // 视图模式
  if (viewMode.value !== 'grid') {
    query.view = viewMode.value
  }

  // 更新路由，不触发导航
  router.replace({query})
}

// 页面初始化
onMounted(async () => {
  // 先加载分类
  await loadCategories()

  // 恢复路由状态
  const query = route.query

  // 检查是否有任何筛选参数
  const hasFilterParams = query.isFavorite || query.categoryId || query.status || query.priority || query.keyword

  if (query.isFavorite === 'true') {
    filter.isFavorite = true
  } else if (!hasFilterParams) {
    // 没有任何筛选参数时，默认激活收藏
    filter.isFavorite = true
  }

  if (query.categoryId) {
    const categoryIdStr = query.categoryId as string
    if (categoryIdStr === '-1') {
      selectedCategoryId.value = -1
      filter.categoryId = -1
    } else {
      selectedCategoryId.value = categoryIdStr
      filter.categoryId = categoryIdStr
    }
  }
  if (query.status) {
    filter.status = (query.status as string).split(',') as TodoStatus[]
  }
  if (query.priority) {
    filter.priority = (query.priority as string).split(',') as TodoPriority[]
  }
  if (query.keyword) {
    filter.keyword = query.keyword as string
  }
  if (query.view && ['list', 'grid', 'flexbox'].includes(query.view as string)) {
    viewMode.value = query.view as 'list' | 'grid' | 'flexbox'
  }

  // 最后加载待办数据（会根据上面设置的筛选条件加载）
  await applyFilter()
})

// 监听视图模式变化，同步到路由
watch(viewMode, () => {
  updateRouteQuery()
})

// 监听筛选条件变化，同步到路由（避免在初始化时触发）
watch([() => filter.status, () => filter.priority, () => filter.keyword], () => {
  updateRouteQuery()
}, {deep: true, flush: 'post'})

// 监听路由参数变化，更新筛选条件和数据
watch(() => route.query, (newQuery) => {
  let needsUpdate = false

  // 收藏标识变化
  const newIsFavorite = newQuery.isFavorite === 'true'
  if ((filter.isFavorite || false) !== newIsFavorite) {
    filter.isFavorite = newIsFavorite || undefined
    needsUpdate = true
  }

  // 分类ID变化
  const newCategoryId = newQuery.categoryId
  if (newCategoryId !== (filter.categoryId === undefined ? undefined : String(filter.categoryId))) {
    if (newCategoryId === undefined) {
      selectedCategoryId.value = null
      filter.categoryId = undefined
    } else if (newCategoryId === '-1') {
      selectedCategoryId.value = -1
      filter.categoryId = -1
    } else {
      selectedCategoryId.value = newCategoryId as string
      filter.categoryId = newCategoryId as string
    }
    needsUpdate = true
  }

  // 状态筛选变化
  const newStatus = newQuery.status ? (newQuery.status as string).split(',') : []
  if (JSON.stringify(filter.status || []) !== JSON.stringify(newStatus)) {
    filter.status = newStatus.length > 0 ? newStatus as any[] : undefined
    needsUpdate = true
  }

  // 优先级筛选变化
  const newPriority = newQuery.priority ? (newQuery.priority as string).split(',') : []
  if (JSON.stringify(filter.priority || []) !== JSON.stringify(newPriority)) {
    filter.priority = newPriority.length > 0 ? newPriority as any[] : undefined
    needsUpdate = true
  }

  // 关键词搜索变化
  const newKeyword = newQuery.keyword as string || ''
  if (filter.keyword !== newKeyword) {
    filter.keyword = newKeyword
    needsUpdate = true
  }

  // 视图模式变化
  const newView = newQuery.view as string || 'grid'
  if (viewMode.value !== newView && ['list', 'grid', 'flexbox'].includes(newView)) {
    viewMode.value = newView as 'list' | 'grid' | 'flexbox'
  }

  // 如果有筛选条件变化，重新加载数据
  if (needsUpdate) {
    applyFilter()
  }
}, {deep: true})

// 重置过滤器（包括路由）
const resetFilter = () => {
  // 重置选中的分类
  selectedCategoryId.value = null

  // 调用原始的重置函数
  originalResetFilter()

  // 清除路由参数
  router.replace({query: {}})
}
</script>

<style scoped>
.todo-list-page {
  padding: 0.5rem;
  background: var(--el-bg-color-page);
  min-height: 100vh;
}

.todo-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.view-controls {
  display: flex;
  align-items: center;
}

/* LogoTitle组件样式覆盖 */
:deep(.logo-title) {
  color: var(--el-text-color-primary) !important;
  gap: 8px;
}

:deep(.logo-title__icon) {
  height: 48px !important;
}

:deep(.logo-title__text) {
  color: var(--el-text-color-primary) !important;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.stats {
  display: flex;
  gap: 8px;
}

.filter-toolbar {
  background: var(--el-bg-color);
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 0.5rem;
  border: 1px solid var(--el-border-color-light);
}

.filter-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.sort-row {
  display: flex;
  align-items: center;
}

.sort-label {
  margin-right: 8px;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.todo-list {
  min-height: 400px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.todo-items {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.todo-items.grid-view {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  align-items: stretch;
}

.todo-items.flexbox-view {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

@media (max-width: 1200px) {
  .todo-items.grid-view {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  }
}

@media (max-width: 768px) {
  .todo-items.grid-view {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .header-right {
    flex-direction: column;
    gap: 8px;
  }

  .view-controls {
    order: 2;
  }
}

/* 快捷键帮助对话框样式 */
.shortcuts-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.shortcut-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.shortcut-item:last-child {
  border-bottom: none;
}

.shortcut-description {
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.shortcut-key {
  font-family: 'Monaco', 'Menlo', 'Consolas', monospace;
  font-size: 12px;
  min-width: 80px;
  text-align: center;
}
</style>